<template>
    <div class="d-player" :ref="that.videoRefKey"></div>
</template>

<script lang="ts">
import DPlayer from 'dplayer';
import { IPropsExt } from '../../type';
import { VueMountedCycle } from '../../utils';
import { defineComponent, SetupContext, getCurrentInstance, ComponentInternalInstance } from 'vue';

class Init {
    props: IProps;
    context: SetupContext;
    current: ComponentInternalInstance;

    videoRefKey = 'video-ref';

    constructor(props: IProps, context: SetupContext, current: ComponentInternalInstance, vueMountedCycle: VueMountedCycle) {
        this.props = props;
        this.context = context;
        this.current = current;

        vueMountedCycle.push(() => {
            if (props.src) {
                new DPlayer({
                    container: current.refs[this.videoRefKey] as HTMLElement,
                    video: { url: props.src },
                });
            }
        });
    }
}

interface IProps extends IPropsExt {
    src: string;
}

export default defineComponent({
    name: 'd-player',

    props: {
        class: { type: String, default: '' },
        src: { type: String, default: '', required: true },
    },

    setup(props: IProps, context: SetupContext) {
        const vueMountedCycle = new VueMountedCycle();
        const current = getCurrentInstance() as ComponentInternalInstance;

        const that = new Init(props, context, current, vueMountedCycle);

        vueMountedCycle.trigger();

        return { that };
    },
});
</script>
